<!-- <template>
  <div style="border: 1px solid red;margin: 20px;padding: 20px;">
    <h1>大文件上传</h1>
    <input type="file" @change="handleFileSelect" />
    <p v-if="uploadProgress !== 0">上传进度: {{ uploadProgress }}%</p>
    <p v-if="mergeProgress">正在合并文件...</p>
  </div>
</template>

<script setup>
import { ref } from "vue"
import { cutFile } from '../utils/cutFile.js'
const uploadProgress = ref(0); // 上传进度
const mergeProgress = ref(false); // 合并状态


const handleFileSelect = async (event) => {
  const file = event.target.files[0];
  if (!file) return;
  // console.time('cutFile')
  const chunks = await cutFile(file)
  // console.timeEnd('cutFile')
  const fileHash = await calculateFileHash(file); // 计算文件唯一 Hash
  // 1. 请求已上传分片
  Promise.all(chunks.map(async (chunk) => {
    const isUploaded = await getUploadedChunks(fileHash, chunk.fileHash)
    console.log(isUploaded, 'isUploaded')
    // if (isUploaded) {
    //   // 如果该分片已上传，跳过
    //   console.dir(`Chunk ${chunk.fileHash} 已经上传, 跳过...`);
    //   uploadProgress.value = Math.round(((chunk.index + 1) / chunks.length) * 100);
    //   return; // 跳过此次循环
    // }
    //发送请求
    const formData = new FormData();
    formData.append("chunk", chunk.blob);
    formData.append("fileName", file.name);
    formData.append("chunkIndex", chunk.index);
    formData.append("fileHash", fileHash);
    formData.append("fileChunkHash", chunk.fileHash);
    await fetch("http://localhost:3200/upload/chunk", {
      method: "POST",
      body: formData,
    })
    uploadProgress.value = Math.round(((chunk.index + 1) / chunks.length) * 100)
  })).then(async (res) => {
    console.log('通知后端合并文件', res)
    return mergeProgress.value = true
    await fetch("http://localhost:3200/upload/merge", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({
        fileHash,
        fileName: file.name,
      }),
    });
    alert("文件上传完成！")
    mergeProgress.value = false;
    uploadProgress.value = 0;
  })
}

const getUploadedChunks = async (fileHash) => {
  try {
    const response = await fetch(`http://localhost:3200/upload/status?fileHash=${fileHash}`);
    const data = await response.json();
    return data
  } catch (error) {
    console.error("Error fetching uploaded chunks:", error);

  }
}

const calculateFileHash = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.onload = () => {
      // 简单生成文件 hash
      const hash = btoa(reader.result).slice(0, 16);
      resolve(hash);
    };
    reader.readAsBinaryString(file)
  })
}
</script> -->
